package com.wtwd.campus.h5_manager.service.impl;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.wtwd.campus.h5_manager.common.Constant;
import com.wtwd.campus.h5_manager.dao.H5ManageSysPermissionMapper;
import com.wtwd.campus.h5_manager.entity.H5Customer;
import com.wtwd.campus.h5_manager.entity.H5ManageRole;
import com.wtwd.campus.h5_manager.entity.H5ManageSysPermission;
import com.wtwd.campus.h5_manager.service.H5ManageRoleService;
import com.wtwd.campus.h5_manager.service.H5ManageSysPermissionService;
import com.wtwd.campus.h5_manager.service.H5MangerSysRolePermissionService;
import com.wtwd.campus.utils.AppKeySecretUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author mjy
 * @since 2022-03-04
 */
@Service
public class H5ManageSysPermissionServiceImpl implements H5ManageSysPermissionService {

    @Resource
    private H5ManageSysPermissionMapper permissionMapper;

    @Autowired
    private H5ManageRoleService roleService;

    @Autowired
    private H5MangerSysRolePermissionService rolePermissionService;

    @Autowired
    private H5CustomerServiceImpl customerService;

    private List<Integer> ids = new ArrayList<>(100);

    /**
     * 为保证已生成的权限id不变,采用插入或更新的方式处理
     */
    @PostConstruct
    private void create() {
        ClassPathResource resource = new ClassPathResource("h5_manage_permission.json");
        JSONObject jsonData = null;
        if (resource.exists()) {
            try {
                jsonData = (JSONObject) JSON.parseObject(resource.getInputStream(), StandardCharsets.UTF_8, JSONObject.class,
                        // 自动关闭流
                        Feature.AutoCloseSource,
                        // 允许注释
                        Feature.AllowComment,
                        // 允许单引号
                        Feature.AllowSingleQuotes,
                        Feature.OrderedField
                );
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println(jsonData.toJSONString());
        //清空权限表记录
        //sysPermissionMapper.clear();
        for (int i = 1; i <= jsonData.size(); i++) {
            JSONObject json = jsonData.getJSONObject(i + "");
            createChild(0, json);
        }
        //删除本次修改中不存在的
        permissionMapper.deleteByNonId(ids);
        //初始化客户
        initCustomer();
        //初始化角色
        initRole();
        //初始化,管理员角色默认收集菜单权限
        initRolePermission();
    }

    /**
     * 初始化菜单
     *
     * @param pid
     * @param json
     */
    private void createChild(Integer pid, JSONObject json) {
        json.put("pid", pid);
        Object children = json.get("children");
        if (pid == 0) {
            json.put("menuType", "1");
        } else {
            json.put("menuType", "2");
        }
        permissionMapper.saveOrUpdate(json);
        ids.add(json.getInteger("id"));
        //插入数据并且返回主键
        if (children instanceof JSONArray) {
            JSONArray array = (JSONArray) children;
            //存在子节点继续遍历
            for (int i = 0; i < array.size(); i++) {
                createChild(json.getInteger("id"), array.getJSONObject(i));
            }
        } else if (children instanceof String) {
            // 插入 按钮类型的权限
            String s = (String) children;
            if ("".equals(s)) return;
            if (s.startsWith("-")) {
                s = "添加,删除,修改" + s.replace("-", "");
            }
            String[] split = s.split(",");
            //默认增删改
            for (String name : split) {
                JSONObject param = new JSONObject();
                param.put("menuType", "10");
                param.put("pid", json.getInteger("id"));
                param.put("name", name);
                permissionMapper.saveOrUpdate(param);
                ids.add(param.getInteger("id"));
            }
        }
    }

    /**
     * 初始化管理员客户(初始化管理员客户id 10)
     */

    private void initCustomer() {
        H5Customer customer = customerService.getH5CustomerById(Constant.H5_MANAGE_CUSTOMER_ADMIN);
        if (customer == null) {
            String appKey = AppKeySecretUtils.getAppKey();
            H5Customer h5Customer = new H5Customer();
            h5Customer.setAppKey(appKey);
            h5Customer.setId(Constant.H5_MANAGE_CUSTOMER_ADMIN);
            h5Customer.setCustomerName(Constant.H5_MANAGE_CUSTOMER_NAME);
            h5Customer.setCreateTime(new Date().getTime());
            customerService.addCustomer(h5Customer);
        }
    }


    /**
     * 默认收集总部默认角色 管理员 客户 处于总部下
     */
    private void initRole() {
        H5ManageRole role = roleService.getRoleByRoleId(Constant.SYS_MANAGE_USER_ROLE_TYPE_ADMIN);
        if (role == null) {
            role = new H5ManageRole();
            role.setRoleId(Constant.SYS_MANAGE_USER_ROLE_TYPE_ADMIN);
            role.setRoleName(Constant.SYS_MANAGE_USER_ROLE_NAME_ADMIN);
            role.seth5Customer(Constant.H5_MANAGE_CUSTOMER_ADMIN);
            roleService.addRole(role);
        }
        H5ManageRole customeRole = roleService.getRoleByRoleId(Constant.SYS_MANAGE_USER_ROLE_TYPE_CUSTOMER);
        if (customeRole == null) {
            role = new H5ManageRole();
            role.setRoleId(Constant.SYS_MANAGE_USER_ROLE_TYPE_CUSTOMER);
            role.setRoleName(Constant.SYS_MANAGE_USER_ROLE_NAME_NAME);
            role.seth5Customer(Constant.H5_MANAGE_CUSTOMER_ADMIN);
            roleService.addRole(role);
        }
    }

    /**
     * 默认收集菜单权限
     */

    private void initRolePermission() {
        //批量添加的菜单权限
        ArrayList<Integer> bathAddPermission = new ArrayList<>();
        H5ManageRole role = roleService.getRoleByRoleId(Constant.SYS_MANAGE_USER_ROLE_TYPE_ADMIN);
        if (role != null) {
            List<H5ManageSysPermission> sysPermissions = permissionMapper.getAllPermission();
            if (sysPermissions != null && sysPermissions.size() > 0) {
                //获取该角色现有所有权限
                List<Integer> perIdList = rolePermissionService.getRolePermissionPerIdByRoleId(role.getRoleId());
                for (H5ManageSysPermission sysPermission : sysPermissions) {
                    //定义需要添加标志
                    boolean flag = true;
                    if (perIdList != null && perIdList.size() > 0) {
                        for (Integer perId : perIdList) {
                            if (sysPermission.getId().equals(perId)) {
                                flag = false;
                                break;
                            }
                        }
                    }
                    if (flag) {
                        bathAddPermission.add(sysPermission.getId());
                    }
                }
            }
            if (bathAddPermission != null && bathAddPermission.size() > 0) {
                rolePermissionService.bathAddRolePermission(role.getRoleId(), bathAddPermission);
            }
        }
    }


}
